package com.sxp.servlet;

import com.sxp.bean.User;
import com.sxp.dao.BookDao;
import com.sxp.bean.Book;
import com.sxp.dao.impl.BookDaoImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author 宋晓盼
 * @since 2019/6/8 16:21
 */
@WebServlet("/book/add")
public class AddBookServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String bookName = req.getParameter("bookname");
        double price = Double.parseDouble(req.getParameter("price"));
        int stock = Integer.parseInt(req.getParameter("stock"));
        String image = req.getParameter("image");

        BookDao bookDao = new BookDaoImpl();
        Integer bookId = bookDao.save(new Book(bookName, stock, price, image));

        HttpSession session = req.getSession();

        User user = (User) session.getAttribute("user");
        if (user != null && user.getAdmin()) {
            if (bookId != null) {
                session.setAttribute("msg", "添加成功！");
                resp.sendRedirect("/obs/message.jsp");
            }else {
                session.setAttribute("msg", "添加失败！");
                resp.sendRedirect("/obs/message.jsp");
            }
        } else {
            session.setAttribute("msg", "未登录！");
            resp.sendRedirect("/obs/message.jsp");
        }


    }
}
